﻿using BasicModuleOrm.Db_Context;
using BasicModuleOrm.Model;
using Microsoft.EntityFrameworkCore;

namespace BasicModuleOrm.ProductRespository
{
    public class ProductEfCoreRespository : IProductRespository
    {
        private EfCoreContext _efCoreContext;

        public ProductEfCoreRespository(EfCoreContext efCoreContext)
        {
            _efCoreContext = efCoreContext;
        }

        public Product AddProduct(Product product)
        {
            // 1、添加商品
            _efCoreContext.Product.Add(product);
            _efCoreContext.SaveChanges();

            return product;
        }

        public void DeleteProduct(int id)
        {
            var product = _efCoreContext.Product.Find(id);

            // 1、开始删除
            _efCoreContext.Product.Remove(product);
            _efCoreContext.SaveChanges();
        }

        public IEnumerable<Product> GetAllProduct()
        {
            return _efCoreContext.Product.ToList();
        }

        public Product GetProduct(int id)
        {
            // 1、查询商品
            var product = _efCoreContext.Product.Find(id);

            return product;
        }

        public void UpdateProduct(int id, Product product)
        {
            //1、设置更新状态
            _efCoreContext.Entry(product).State = EntityState.Modified;

            try
            {
                //2、开始更新
                _efCoreContext.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                throw;
            }

        }
    }
}
